<template>
  <div class="home">
    <header class="head">
      <div class="container">
        <div class="db">
          <div class="logo">{{ $t("title.doc63") }}</div>
          <div class="close">
            <img
              @click="retreat()"
              src="../../assets/images/closeicon.png"
              alt=""
            />
          </div>
        </div>
      </div>
    </header>

    <main class="container">
      <div class="logo">
        <section class="header-section">
          <h1 class="title">{{ $t("title.doc64") }}</h1>
          <p class="remark">{{ $t("title.doc65") }}</p>
        </section>

        <section class="form-section">
          <ul>
            <li>
              <div class="name">{{ $t("page1.doc72") }}</div>
              <div class="input">
                <input
                  type="text"
                  :placeholder="$t('page1.doc65')"
                  v-model="formData.mobile"
                />
              </div>
            </li>

            <li>
              <div class="name">{{ $t("page1.doc27") }}</div>
              <div class="input">
                <div class="in">
                  <input
                    type="text"
                    :placeholder="$t('page1.doc28')"
                    v-model="formData.code"
                  />
                </div>
                <template v-if="!uiState.time_show">
                  <div class="str" @click="send_click">
                    {{ $t("page1.doc29") }}
                  </div>
                </template>
                <template v-else>
                  <div class="str">
                    <van-count-down
                      ref="countDown"
                      :time="time"
                      format="ss"
                      @finish="finish_time"
                    >
                      <template #default="timeData">
                        <span>{{ timeData.seconds }} <var>s</var></span>
                      </template>
                    </van-count-down>
                  </div>
                </template>
              </div>
            </li>

            <li>
              <div class="name">{{ $t("page1.doc30") }}</div>
              <div class="input">
                <input
                  type="password"
                  :placeholder="$t('page1.doc31')"
                  v-model="formData.password"
                />
              </div>
            </li>
          </ul>

          <button
            class="btn"
            @click="onBtn"
            :disabled="uiState.isDisable"
          >
            {{ $t("page.doc83") }}
          </button>
        </section>
      </div>
    </main>

    <van-popup
      v-model="uiState.if_area"
      position="bottom"
      round
    >
      <div class="area_pop">
        <div class="title rel">
          {{ $t("page.doc41") }}
          <div class="abs" @click="() => uiState.if_area = false">
            <van-icon name="cross" />
          </div>
        </div>

        <div class="so db">
          <div class="ico"></div>
          <div class="flexs">
            <input
              type="text"
              :placeholder="$t('page.doc42')"
              v-model="soAreaId"
            />
          </div>
          <div
            v-if="soAreaId"
            class="closes"
            @click="() => soAreaId = ''"
          >
            <img src="../../assets/images/ico_close.png" alt="" />
          </div>
        </div>

        <ul>
          <li
            v-for="(item, k) in searchResult"
            :key="k"
            class="db"
            @click="area_set(item.mobilePrefix)"
          >
            <div class="ico">
              <img :src="item.iconUrl" alt="" />
            </div>
            <div class="flexs txt">
              {{ item.name }}（+{{ item.mobilePrefix }}）
            </div>
          </li>
        </ul>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { mapActions, mapMutations } from "vuex";
import { antiShake } from "@/utils/fun.js";

// 提取常量
const CONSTANTS = {
  PHONE_REGEX: /^1[3-578]\d{9}$/,
  PASSWORD_REGEX: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/,
  EMAIL_REGEX: /^(\w-*\.*\+*)+@(\w-?)+(\.\w{2,})+$/,
  COUNTDOWN_TIME: 60 * 1000,
  ACCOUNT_TYPES: {
    PHONE: 0,
    EMAIL: 1
  },
  VERIFY_TYPE: {
    RESET_PASSWORD: 6
  }
};

export default {
  data() {
    return {
      title: "",
      titleRight: this.getTitleRight(),
      tabData: this.getTabData(),
      cid: CONSTANTS.ACCOUNT_TYPES.EMAIL,

      // 表单数据
      formData: {
        areaId: "44",
        mobile: "",
        email: "",
        code: "",
        password: "",
        s_password: "",
        cap: "",
        invateCode: ""
      },

      // UI状态
      uiState: {
        if_area: false,
        time_show: false,
        time_status: false,
        checked: true,
        isDisable: false
      },

      // 其他数据
      areaData: [],
      time: CONSTANTS.COUNTDOWN_TIME,
      soAreaId: "",
      isUa: "",
      registration_data: {
        pwdType: "password"
      }
    };
  },

  computed: {
    searchResult() {
      if (!this.soAreaId) return this.areaData;

      return this.areaData.filter(item =>
        item.mobilePrefix.includes(this.soAreaId)
      );
    }
  },

  watch: {
    soAreaId: {
      immediate: true,
      handler(val) {
        this.code_data = this.areaData.filter(p =>
          p.mobilePrefix.includes(val)
        );
      }
    }
  },

  mounted() {
    this.initData();
    this.checkPlatform();
    this.loadStoredData();
  },

  methods: {
    ...mapMutations([
      "SET_USERDATA",
      "SET_TOKEN",
      "SET_LOGIN",
      "SET_MOBILE",
      "SET_EMAIL",
      "SET_AREAID",
      "SET_ISAPPINFO"
    ]),
    ...mapActions(["Get_userData"]),

    // 初始化方法
    getTitleRight() {
      return "<img src=" + require("../../assets/images/ico_lang.png") + ">" + this.$t("page.doc43");
    },

    getTabData() {
      return [
        { name: this.$t("page.doc95"), cid: CONSTANTS.ACCOUNT_TYPES.EMAIL },
        { name: this.$t("page.doc94"), cid: CONSTANTS.ACCOUNT_TYPES.PHONE }
      ];
    },

    initData() {
      this.getArea();
      window.getIsApp = this.getIsApp;
    },

    loadStoredData() {
      const storedData = {
        inviteCode: this.$route.query.inviteCode,
        mobile: localStorage.getItem("mobile"),
        email: localStorage.getItem("email"),
        areaId: localStorage.getItem("areaId"),
        invateCode: localStorage.getItem("invateCode")
      };

      Object.entries(storedData).forEach(([key, value]) => {
        if (value) this.formData[key] = value;
      });
    },

    checkPlatform() {
      const platform = this.common.getPlatform;

      if (platform === "IOS") {
        this.checkIOS();
      } else {
        this.checkAndroid();
      }
    },

    checkIOS() {
      try {
        window.webkit.messageHandlers.getIsApp.postMessage(JSON.stringify(json));
        if (this.isUa) {
          this.SET_ISAPPINFO(true);
        }
      } catch (error) {
        console.log("ios error");
      }
    },

    checkAndroid() {
      try {
        this.isUa = window.android.getIsApp();
        if (this.isUa) {
          this.SET_ISAPPINFO(true);
        }
      } catch (error) {
        console.log("Android error");
      }
    },

    // UI 相关方法
    retreat() {
      this.$router.go(-1);
    },

    changeType() {
      this.registration_data.pwdType =
        this.registration_data.pwdType === "password" ? "text" : "password";
    },

    onTab(item) {
      this.cid = item.cid;
    },

    finish_time() {
      this.uiState.time_status = false;
      this.uiState.time_show = false;
    },

    // 验证码相关
    send_click() {
      if (this.uiState.time_status) {
        this.$toast.success(this.$t("page.doc44"));
        return;
      }
      this.send_code();
    },

    async send_code() {
      if (this.uiState.time_status) {
        this.$toast.success(this.$t("page.doc44"));
        return;
      }

      if (!this.validateAccount()) return;

      const send_arr = {
        accountType: this.cid,
        prefix: this.formData.areaId,
        account: this.formData.mobile.replace(/\s*/g, ""),
        type: CONSTANTS.VERIFY_TYPE.RESET_PASSWORD,
        captchaKey: this.formData.captchaKey,
        captchaCode: this.formData.cap
      };

      try {
        const res = await this.$post(this.URL.user.code_send, send_arr);

        if (res.code === 0) {
          this.handleCodeSendSuccess();
        } else {
          this.$toast(res.message);
        }
      } catch (error) {
        console.error('发送验证码失败:', error);
      }
    },

    validateAccount() {
      if (this.cid === CONSTANTS.ACCOUNT_TYPES.PHONE) {
        const isValidPhone = this.formData.mobile.toString().length >= 6 &&
                           this.formData.mobile.toString().length <= 13;
        if (!isValidPhone) {
          this.$toast.fail(this.$t("page.doc45"));
          return false;
        }
      } else {
        if (!CONSTANTS.EMAIL_REGEX.test(this.formData.mobile.replace(/\s+/g, ""))) {
          this.$toast.fail(this.$t("page.doc46"));
          return false;
        }
      }
      return true;
    },

    handleCodeSendSuccess() {
      this.$toast.success(this.$t("page.doc47"));
      this.uiState.time_show = true;
      this.uiState.time_status = true;
      this.$refs.countDown.reset();
      this.$refs.countDown.start();
    },

    // 区域选择相关
    area_set(id) {
      this.formData.areaId = id;
      this.uiState.if_area = false;
    },

    async getArea() {
      try {
        const res = await this.$post(this.URL.user.country_list, {});
        if (res.code === 0) {
          this.areaData = res.data;
          this.formData.areaId = res.data[0].mobilePrefix;
        } else {
          this.$toast(res.message);
        }
      } catch (error) {
        console.error('获取区域列表失败:', error);
      }
    },

    // 提交表单
    onBtn: antiShake(async function() {
      if (!this.validateForm()) return;

      try {
        const res = await this.$post(this.URL.user.forget, {
          accountType: this.cid,
          prefix: this.formData.areaId,
          account: this.formData.mobile,
          code: this.formData.code,
          password: this.$md5(this.formData.password)
        });

        if (res.code === 0) {
          this.$toast(res.message);
          this.path_url("/user/login");
        } else {
          this.$toast(res.message);
        }
      } catch (error) {
        console.error('重置密码失败:', error);
      }
    }),

    validateForm() {
      if (!this.validateAccount()) return false;

      const isValidPassword = CONSTANTS.PASSWORD_REGEX.test(this.formData.password);
      if (!isValidPassword) {
        this.$toast(this.$t("page.doc48"));
        return false;
      }

      return true;
    },

    path_url(url) {
      this.$router.push({
        path: url,
        query: {}
      });
    }
  }
};
</script>

<style lang="less" scoped>
.home {
  min-height: 100vh;
  background: #101116;
}

.head {
  padding: 0.22rem 0;

  .container {
    .db {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      font-size: 0.34rem;
      color: #ffffff;

      img {
        height: 0.44rem;
      }
    }
  }
}

.logo {
  font-family: PingFangSC-Semibold, PingFang SC;
  font-weight: 400;
  color: #ffffff;

  .title {
    //styleName: 加粗/14;
    font-family: Inter;
    font-size: 14px;
    font-weight: 700;
    color: #FFDD9A;
  }

  .remark {
    //styleName: 常规/12;
    font-family: Inter;
    font-size: 12px;
    font-weight: 400;
    color: #ffffffcc;
    margin-top: 8px;
  }

  ul {
    //border-top: var(--COborder1);
    //padding: 0rem 0.32rem;
    //background: var(--CObackgroundLinear2);
    border-radius: 0rem 0rem 0.2rem 0.2rem;
    margin: 0.5rem 0rem 0.25rem;

    li {
      padding: 0rem 0rem 0.28rem 0rem;
      //border-bottom: 0.01rem solid rgba(255, 255, 255, 0.1);

      .name {
        font-size: 0.28rem;
        color: var(--COborder2);
        margin-bottom: 0.22rem;
      }

      .input {
        display: flex;
        align-items: center;
        height: 48px;
        background: #181c21;
        padding: 0.24rem 0.32rem;
        margin-bottom: 0.24rem;
        border-radius: 0.2rem;
        border: 1px solid #282c31;

        input {
          width: 100%;
          height: 0.38rem;
          font-size: 0.28rem;
          font-weight: 400;
          text-align: left;
          color: var(--COborder1);
          background: none;
          border: 0;
          &::placeholder {
            font-size: 0.24rem;
          }
        }

        .in {
          flex: 1;
        }

        .str {
          background: linear-gradient(90deg, #FAD7A6 0%, #DAAB6A 100%);
          border-radius: 999px;
          padding: 0.12rem 18px;
          text-align: center;
          font-size: 0.24rem;
          font-weight: 400;
          color: #000;

          /deep/ .van-count-down {
            color: var(--COborder3);
          }
        }
      }
    }
  }

  .btn {
    width: 100%;
    font-size: 0.3rem;
    font-weight: 700;
    color: #000;
    border: 0;
    text-align: center;
    padding: 0.25rem 0rem;
    background: linear-gradient(90deg, #FAD7A6 0%, #DAAB6A 100%);
    border-radius: 0.16rem;
    margin: 0.32rem 0rem 0.52rem 0rem;
  }
}

.container {
  color: #989898;
}

.box {
  height: 70vh;
  width: 100%;

  .flex {
    width: 100%;
  }

  .info {
    padding: 0 0.2rem;
  }

  ul {
    padding-top: 1rem;
    width: 100%;

    li {
      height: 0.88rem;
      background: rgba(0, 0, 0, 0.57);
      border-radius: 0.44rem;
      margin-bottom: 0.4rem;
      padding: 0 0.5rem;

      .area_name {
        border-right: 0.02rem solid #989898;
        padding-right: 0.2rem;
        margin-right: 0.2rem;

        i {
          font-size: 0.24rem;
          margin-left: 0.06rem;
        }
      }

      .str {
        height: 0.88rem;
        background: #585b5e;
        border-radius: 44px;
        margin-right: -0.5rem;
        line-height: 0.88rem;
        padding: 0 0.4rem;
        color: #fff;

        /deep/ .van-count-down {
          color: #fff;
          height: 0.88rem;
          line-height: 0.88rem;
        }
      }

      input {
        width: 100%;
        height: 0.38rem;
        font-size: 0.28rem;
        font-weight: 400;
        text-align: left;
        color: #989898;
        background: none;
        border: 0;
      }
    }
  }
}

.bottom {
  .txt {
    margin-top: 0.4rem;
    text-align: center;

    p {
      padding-bottom: 0.2rem;
    }
  }

  /deep/ .van-checkbox__label {
    color: #9ba0a5;
    font-size: 0.24rem;
  }

  /deep/ .van-checkbox {
    justify-content: center;
  }
}

.close {
  background: red;
  width: 32px;
  height: 32px;
  padding: 5.33px;
  border-radius: 10px;
  background: var(---1, #181c21);
}

.input-wrapper {
  background: var(--1, #181c21);
  padding: 0.24rem 0.32rem;
  border-radius: 0.2rem;
  margin: 24px 0;

  .input {
    display: flex;
    align-items: center;

    input {
      width: 100%;
      height: 0.38rem;
      font-size: 0.28rem;
      font-weight: 400;
      text-align: left;
      color: #bdbdbd;
      background: none;
      border: 0;
    }

    .in {
      flex: 1;
    }

    .str {
      background: linear-gradient(225deg, #ff4565 0%, #ef1746 100%);
      border-radius: 0.3rem;
      padding: 0.12rem 0.24rem;
      color: #fff;
      text-align: center;
      font-size: 0.24rem;
      font-weight: 400;

      /deep/ .van-count-down {
        color: #fff;
      }
    }
  }
}
</style>
